import React from "react";
import { connect } from "dva";
import { Button, Icon, Radio, Form, Input, Upload, message } from "antd";
import "./Images.scss";
import Uploaddd from "./UploadImg";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

@connect(({ add }) => ({
  add: add
}))
class Images extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      radioValue: 1,
      index: 0,
      marginLeft: 0,
      marginRight: 0,
      imgList: [
        {
          key: 0,
          img_path: "",
          img_title: "",
          img_intro: ""
        }
      ],
      titleLength: 0,
      titleValue: "",
      keyLength: 0,
      introLength: 0,
      num: 0
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    window.PubSub.subscribe("imgAll", this.setImgAll);
  }
  componentWillUnmount() {
    this.props.dispatch({ type: "add/resetPushClick" });
  }
  onChangeRadio = e => {
    this.setState({
      radioValue: e.target.value
    });
    if (e.target.value == 1) {
      this.setFields({
        url: ""
      });
    }
  };
  /**
   * 获取title length
   */
  getTitleLength = e => {
    let length = e.target.value.length;
    if (length <= 60) {
      this.setState({
        titleLength: length,
        titleValue: e.target.value
      });
    }
    window.PubSub.publish("tabTitle", e.target.value);
  };
  /**
   * 增加列表
   */
  addImgList = () => {
    let imgArr = [...this.state.imgList];
    let index = this.state.num;
    imgArr.push({
      key: index + 1,
      img_path: "",
      img_title: "",
      img_intro: ""
    });
    this.setState({
      imgList: imgArr,
      num: index + 1
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });

    // console.log(index);
  };
  /**
   * 删除列表
   */
  deletImgList = index => {
    let imgArr = [...this.state.imgList];

    imgArr.map((item, indexs) => {
      if (item.key == index) {
        imgArr.splice(indexs, 1);
      }
    });
    this.setState({
      imgList: imgArr,
      num: this.state.num - 1
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  /**
   * 设置值
   */
  setListInput = (e, key) => {
    let imgArr = [...this.state.imgList];
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.img_title = e.target.value;
      }
    });
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  setListText = (e, key) => {
    let imgArr = [...this.state.imgList];
    let imgIntroArr = document.getElementsByClassName("imgIntro");
    console.log(imgIntroArr);

    imgArr.map((item, index) => {
      console.log(imgIntroArr[index].attributes["data-id"].value);
      console.log(item.key);
      if (item.key == imgIntroArr[index].attributes["data-id"].value) {
        item.img_intro = imgIntroArr[index].innerText;
        imgIntroArr[index].innerText
      }
    });
    console.log(imgArr);

    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  setListUrl = (data, key) => {
    let imgArr = [...this.state.imgList];
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.img_path = data;
      }
    });
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  /**
   * 关闭
   */
  close = key => {
    this.props.dispatch({
      type: "add/close",
      key: key
    });
  };
  /**
   * 推荐左滑按钮
   */
  left = () => {
    let marginLeft = this.state.marginLeft + 145;
    if (marginLeft >= 0) {
      this.setState({
        marginLeft: 0
      });
    } else {
      this.setState({
        marginLeft: marginLeft
      });
    }
  };

  /**
   * 推荐右滑按钮
   */
  right = () => {
    let marginLeft = this.state.marginLeft - 145;
    let length = (this.props.add.gltjData.length - 4) * 145;
    if (marginLeft <= -length) {
      this.setState({
        marginLeft: -length
      });
    } else {
      this.setState({
        marginLeft: marginLeft
      });
    }
  };
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    this.props.add.gltjData.map((item, index) => {
      about.push(item.information_id);
    });
    data["about"] = about.join();
    data["img_arr"] = this.state.imgList;
    data["type"] = 2;
    return data;
  };
  getFieldsValue = () => {
    this.setListText();
    let data = this.props.form.getFieldsValue();
    this.props.form.validateFields();
    let validateArr = this.props.form.getFieldsError();
    let intro = document.getElementById("inputIntro").innerText;
    console.log(intro);
    data.intro = intro;

    let isDown = true;
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {
        //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false;
          return;
        }
      }
    }
    if (isDown) {
      let about = [];
      this.props.add.gltjData.map((item, index) => {
        about.push(item.information_id);
      });
      data["about"] = about.join();
      data["img_arr"] = this.state.imgList;
      data["type"] = 2;
      return data;
    }
  };
  /**
   * 重置表单
   */
  resetFields = () => {
    this.props.form.resetFields();
    this.setState({
      titleValue: ""
    });
  };
  /**
   * 设置表单值
   */
  setFields = data => {
    this.props.form.setFieldsValue(data);
    this.setState({
      titleValue: data.information_title
    });
    if (data.url) {
      this.setState({
        radioValue: 2
      });
    }
    document.getElementById("inputIntro").innerText=data.intro
    if (data.img_arr && data.img_arr.length) {
      let arr = [];
      data.img_arr.map((item, index) => {
        arr.push({
          key: index,
          img_path: item.img_path,
          img_title: item.img_title,
          img_intro: item.img_intro
        });
      });
      this.setState({
        imgList: arr,
        num: arr.length
      });
      this.props.dispatch({ type: "add/setUploadImageList", data: arr });
    }
    if (data.about) {
      this.props.dispatch({ type: "add/setPushClick", data: data.about_list });
    }
  };
  /**
   * 订阅
   */
  setImgAll = data => {
    if (data.type === "biz_sobey_picture") {
      let imgList = [...this.state.imgList];
      let length = imgList.length;
      let num = this.state.num;
      if (num < length) {
        imgList[num].img_path = data.keyFrameUrl;
        this.setState({
          num: num + 1,
          imgList: imgList
        });
        this.props.dispatch({ type: "add/setUploadImageList", data: imgList });
      } else {
        imgList[0].img_path = data.keyFrameUrl;
        this.setState({
          num: 1
        });
      }
    }
  };
  /**
   * 从内容库选择
   */
  getfromContent = () => {
    if (window.bar) {
      window.bar.show("picture", "ggsc"); //图片
      this.props.dispatch({ type: "add/saveMchType", data: "imgAll" });
    }
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    const myValidateFields = (rule, values, callback) => {
      var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (values) {
        if (!reg.test(values)) {
          callback("请输入正确的URL");
        }
      }
      callback();
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      }
    };
    let gltjData = this.props.add.gltjData;
    if (!gltjData) {
      gltjData = [];
    }

    //将当前this传递给父类
    this.props.onRef(this);

    return (
      <div className="Images1">
        <div className="formBox">
          <Form>
            <FormItem label="">
              {getFieldDecorator("url", {
                rules: [
                  {
                    validator: myValidateFields
                  }
                ]
              })(
                <Input
                  placeholder="请输入url链接"
                  style={this.state.radioValue === 1 ? { display: "none" } : {}}
                />
              )}
            </FormItem>
            {this.props.add.configJson.mchSwitch ? (
              <Button
                style={this.state.radioValue === 2 ? { display: "none" } : {}}
                onClick={this.getfromContent}
              >
                {/* 从内容库选择 */}
                ᠠᠭᠤᠯᠭ᠎ᠠ ᠶ᠋ᠢᠨ ᠬᠥᠮᠦᠷᠭᠡ ᠡᠴᠡ ᠰᠣᠩᠭᠤᠬᠤ
              </Button>
            ) : (
              ""
            )}
            {/* <p style={this.state.radioValue === 2 ? { display: "none" } : {}}>
              注：请上传1-15张图片，上传图片推荐尺寸，推荐2M,图片格式为jpg/png
            </p> */}
            {/* 内容编辑模式、url模式 */}
            <RadioGroup
              onChange={this.onChangeRadio}
              value={this.state.radioValue}
              style={{ marginBottom: "20px" }}
            >
              <Radio value={1}> ᠠᠭᠤᠯᠭ᠎ᠠ ᠨᠠᠢᠷᠠᠭᠤᠯᠬᠤ ᠬᠡᠯᠪᠡᠷᠢ</Radio>
              <Radio value={2}>URL ᠬᠡᠯᠪᠡᠷᠢ</Radio>
            </RadioGroup>
            {/* 摘要 */}
            <FormItem {...formItemLayout} label="ᠳᠥᠬᠦᠮ ᠲᠠᠨᠢᠯᠴᠠᠭᠤᠯᠭ᠎ᠠ">
              <p
                id="inputIntro"
                contenteditable="true"
                className="inputIntro"
              ></p>
              <span className="showTextLength">
                {this.state.introLength}/250
              </span>
            </FormItem>
            {/* 关键字 */}
            <FormItem {...formItemLayout} label=" ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ ᠶ᠋ᠢᠨ  ᠦᠰᠦᠭ">
              {getFieldDecorator("key_words")(
                <Input
                  className="keyInput"
                  onChange={e => {
                    let data = e.target.value;
                    if (data.length <= 50) {
                      this.setState({
                        keyLength: data.length
                      });
                    }
                  }}
                  maxLength={50}
                />
              )}
              <span className="showKeyLength">{this.state.keyLength}/50</span>
            </FormItem>
            {/* 标题 */}
            <FormItem label="">
              <p className="title_show">
                <span className="required">*</span>
                {getFieldDecorator("information_title", {
                  rules: [
                    {
                      required: true,
                      message: "ᠭᠠᠷᠴᠠᠭ ᠢ᠋ᠶ᠋ᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ"
                    }
                  ]
                })(
                  <Input
                    placeholder="ᠭᠠᠷᠴᠠᠭ ᠢ᠋ᠶ᠋ᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ"
                    className="artical_title"
                    onChange={this.getTitleLength}
                    size="large"
                    style={{ width: "100%", paddingRight: "90px" }}
                    maxLength={60}
                  />
                )}
                <span className="rightInput">{this.state.titleLength}/60</span>
              </p>
            </FormItem>
          </Form>
        </div>
        {/* 图片列表 */}
        <div
          style={this.state.radioValue === 2 ? { display: "none" } : {}}
          className="imgBox"
        >
          {this.state.imgList.map((item, index) => {
            return (
              <div className="imgList" key={index}>
                <div className="imgList_right">
                  <div className="imgList_text">
                    {/* 图片描述： */}
                    <span>ᠵᠢᠷᠤᠭ ᠤ᠋ᠨ ᠲᠠᠨᠢᠯᠴᠠᠭᠤᠯᠭ᠎ᠠ</span>
                    <p
                      key={index}
                      data-id={index}
                      contenteditable="true"
                      className="imgIntro"
                    ></p>
                  </div>
                  <div className="imgList_title">

                    <span> ᠵᠢᠷᠤᠭ ᠤ᠋ᠨ ᠭᠠᠷᠴᠠᠭ</span>
                    <Input
                      style={{ width: "80%" }}
                      value={item.img_title}
                      onChange={e => this.setListInput(e, item.key)}
                    />
                  </div>
                  <span
                    className="delet_imgList"
                    onClick={() => this.deletImgList(item.key)}
                  >
                    {/* 删除 */}
                    ᠬᠠᠰᠤᠬᠤ
                  </span>
                </div>
                <div className="img_upload">
                  <Uploaddd
                    setUrl={data => this.setListUrl(data, item.key)}
                    img={item.img_path}
                  />
                </div>
              </div>
            );
          })}
          <div className="add_imgList" onClick={this.addImgList}>
            <Icon type="plus" theme="outlined" />
          </div>
        </div>
        {/* <h3 style={{ marginTop: "17px" }}>资讯推荐</h3>
        <div className="gl-video">
          <div className="gl-left" onClick={this.left}>
            <Icon type="left" theme="outlined" />
          </div>
          <div className="gl-main">
            <div
              className="gl-content"
              style={{ marginLeft: this.state.marginLeft }}
            >
              {gltjData.map((item, key) => {
                return (
                  <div className="gl-item">
                    <img className="" src={item.thumbnail} />
                    <div className="gl-title">{item.video_title}</div>
                    <div
                      className="close"
                      onClick={() => {
                        this.close(key);
                      }}
                    >
                      <Icon className="delete" type="delete" theme="outlined" />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="gl-right" onClick={this.right}>
            <Icon type="right" theme="outlined" />
          </div>
        </div> */}
      </div>
    );
  }
}

const ImagesFrom = Form.create()(Images);
export default ImagesFrom;
